//
//  MyCompanyViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/8.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "MyCompanyViewController.h"
#import <UIImageView+WebCache.h>
#import "UserInfoUpdateResde.h"
#import "AppDelegate.h"
#import "LCActionSheet.h"
#import "SDPhotoBrowser.h"
#import "IWUploadParam.h"
#import "UserInfoUpdateResde.h"
@interface MyCompanyViewController ()<LCActionSheetDelegate,SDPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *companyname;
@property (weak, nonatomic) IBOutlet UITextField *companyadress;
@property (weak, nonatomic) IBOutlet UIView *bgview;
@property (weak, nonatomic) IBOutlet UIImageView *card_img;
@property (weak, nonatomic) IBOutlet UITextField *job;
@property (nonatomic,strong) UIImage *card;
@property (nonatomic,copy) NSString *car_img_url;
@property (nonatomic,strong) UIImagePickerController *picker;
@end

@implementation MyCompanyViewController
+(instancetype)viewcontroller{
    MyCompanyViewController *vc=[XHMianStory instantiateViewControllerWithIdentifier:@"mycompany"];
    return vc;
}
- (IBAction)pickimg:(id)sender {
    if (self.card) {
        [self imgpickisshowHas:YES];
    }else{
        [self imgpickisshowHas:NO];
    }
    
    
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

-(void)imgpickisshowHas:(BOOL)isshow{
    
    NSArray *titlearray;
    
    if (isshow) {
        titlearray=@[@"重新上传",@"查看大图"];
        
    }else{
        titlearray=@[@"拍照",@"从相册中选择"];
        
    }
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil buttonTitles: titlearray redButtonIndex:-1 delegate:self];
    [sheet show];
    sheet.isTag=isshow;
}
-(void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%d",actionSheet.tag);
    if (buttonIndex==actionSheet.btnCount-1) {
        return;
    }
    if (actionSheet.isTag) {
        if (buttonIndex==0) {
            [self imgpickisshowHas:NO];
        }else{
            [self showImage];
        }
    }else{
        if (buttonIndex==0) {
            [self showCarmera:actionSheet.tag];
        }else{
            [self showimagepicker:actionSheet.tag];
        }
    }
}

-(void)showimagepicker:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}

-(void)showCarmera:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor whiteColor];
        
        _picker.delegate =self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}


-(void)showImage{
    SDPhotoBrowser *browser=[[SDPhotoBrowser alloc]init];
    
    browser.sourceImagesContainerView = self.bgview; // 原图的父控件
    browser.imageCount = 1 ; // 图片总数
    browser.currentImageIndex = 0;
    browser.delegate = self;
    [browser show];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(righgtclick)];
    self.companyname.text=self.user.user_skype;
    self.companyadress.text=self.user.user_company_address;
    self.job.text=self.user.user_job;
    if (![self.user.user_card_img isEqualToString:@""]) {
        [self.card_img sd_setImageWithURL:[NSURL URLWithString:[NSString getImageURLstr:self.user.user_card_img]] placeholderImage:[UIImage imageNamed:@"placehoder"]completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.card=image;
            self.card_img.hidden=NO;
        }];

    }else{
        self.card_img.hidden=YES;
    }
    
    // Do any additional setup after loading the view.
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(void)righgtclick{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
 
  
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
    if ((self.companyname.text.length>0&&[self.companyname.text isEqualToString:self.user.user_skype])||(self.companyadress.text.length>0&&[self.companyadress.text isEqualToString:self.user.user_company_address])||(self.job.text.length>0&&[self.job.text isEqualToString:self.user.user_job])) {
        hud.labelText=@"正在修改";
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"action"]=@"p_company_change";
        params[@"user_skype"]=self.companyname.text;
        params[@"user_company_address"]=self.companyadress.text;
        params[@"user_job"]=self.job.text;
        params[@"user_type"]=@"person";
        params[@"user_id"]=self.user.user_id;
        [PostUitls Post:userinfourl parameters:params success:^(id response) {
            NSDictionary *dict=response;
            UserInfoUpdateResde *resde=[UserInfoUpdateResde resdeWithDict:dict];
             hud.mode=MBProgressHUDModeText;
            if ([resde.state integerValue]==400) {
               
                hud.labelText=@"修改成功";
                [self savedata];
                
            }else{
                hud.labelText=@"修改失败";
            }
            [hud hide:YES afterDelay:0.5];
        } failure:^(NSError *error) {
            hud.labelText=@"修改失败";
            [hud hide:YES afterDelay:0.5];
        }];
    }else{
        [hud hide:YES];
    }
}
-(void)savedata{
    self.user.user_job=self.job.text;
    self.user.user_company_address=self.companyadress.text;
    self.user.user_skype=self.companyname.text;
    if (self.car_img_url&&![self.car_img_url isEqualToString:@""]) {
        self.user.user_card_img=self.car_img_url;
    }
    AppDelegate *deleage=[[UIApplication sharedApplication]delegate];
    [deleage saveContext];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        self.card_img.image=image;
        [self uploadimage:image];
    }];
}
-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    return self.card_img.image;
}

-(void)uploadimage:(UIImage *)image{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    hud.labelText=@"正在修改..";
    
    
    hud.margin = 10.f;
    
    hud.removeFromSuperViewOnHide = YES;
    

    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"user_id"]=self.user.user_id;
    params[@"user_type"]=@"person";
    params[@"action"]=@"p_card_img";
    
    IWUploadParam *imgparam=[[IWUploadParam alloc]init];
    imgparam.data=[UIImage compressData:image toMaxFileSize:DefailutPicSize];
    imgparam.mineType=@"jpeg";
    imgparam.paramName=@"card_img";
    imgparam.fileName=@"car_img.jpg";
    
    [PostUitls upload:userinfourl parameters:params uploadarray:@[imgparam] success:^(id responseobj) {
        hud.mode=MBProgressHUDModeText;
        UserInfoUpdateResde *mode=[UserInfoUpdateResde resdeWithDict:responseobj];
        if ([mode.state integerValue]==400) {
            hud.labelText=@"修改成功";
            self.user.user_card_img=mode.data;
            [self savedata];
        }else{
            hud.labelText=mode.msg;
        }
        [hud hide:YES afterDelay:1];
    } failure:^(NSError *error) {
        hud.mode=MBProgressHUDModeText;
         hud.labelText=@"网络异常";
        [hud hide:YES afterDelay:1];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
